package com.sdkj.fixed.asset.login.controller;

import com.google.common.collect.Lists;
import com.sdkj.fixed.asset.api.login.LoginApi;
import com.sdkj.fixed.asset.api.login.in_vo.LoginParam;
import com.sdkj.fixed.asset.api.login.out_vo.CompanyBaseListResult;
import com.sdkj.fixed.asset.api.login.out_vo.LoginUserResultMobile;
import com.sdkj.fixed.asset.api.login.out_vo.LoginUserResultPC;
import com.sdkj.fixed.asset.api.login.out_vo.MenuResultEntity;
import com.sdkj.fixed.asset.api.login.pojo.LoginRole;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.api.system.out_vo.UsageResult;
import com.sdkj.fixed.asset.common.base.BaseResultVo;
import com.sdkj.fixed.asset.login.service.LoginService;
import com.sdkj.fixed.asset.login.util.*;


import com.sdkj.fixed.asset.pojo.system.UsageManagement;
import com.sdkj.fixed.asset.pojo.system.UserManagement;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录
 * @author 张欣
 */
@Controller
public class LoginController  implements LoginApi {


    @Autowired
    private LoginService loginService;


    @Autowired
    private RedisUtil redis;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtil cacheUtil;
    /**
     * PC端登录接口
     * @param loginParam
     * @return
     */
    @ApiOperation(value = "PC端登录接口",notes = "PC端登录接口")
    @Override
    public BaseResultVo loginPC(@Validated LoginParam loginParam) throws Exception {
        LoginUser resultVo = new LoginUserResultPC();
        String tel = loginParam.getTel();
        //校验登录
        if(loginService.isLegality(tel,loginParam.getPassword(),true)) {
            //获取当前登录用户
            UserManagement user = loginService.getUserByTel(tel,true);
            //查询当前登录用户角色信息
            List<LoginRole> roles = loginService.getRoles(user.getId());
            List<String> roleLevel = Lists.transform(roles, LoginRole->LoginRole.getRoleLevel());
            boolean flag = roleLevel.contains(com.sdkj.fixed.asset.common.core.RoleType.SYSADMIN.getRoleType());

            //查询登录用户所属公司
            Map<String, Object> companyInfoForHomePage = loginService.getCompanyInfoForHomePage(user.getId(), flag);
            List<CompanyBaseListResult> companys = (List<CompanyBaseListResult>) companyInfoForHomePage.get("companyId");
            resultVo.setLoginRoles(roles);
            resultVo.setUserId(user.getId());
            resultVo.setUserName(user.getName());
            resultVo.setBelongToCompanyId(companyInfoForHomePage.get("belongToCompany").toString());

            //公司使用情况，版本号
            if(flag){
                resultVo.setVersion(3);
            } else {
                UsageManagement usageManagement = loginService.getUsage(companys.get(0).getCompanyId());
                resultVo.setVersion(usageManagement != null ? usageManagement.getType(): 3);
            }

            ((LoginUserResultPC)resultVo).setCompanys(companys);
            //基础信息
            saveToken((LoginUserResultPC)resultVo);
            return BaseResultVo.success(resultVo);
        }else{
            return BaseResultVo.failure("用户名或密码错误");
        }

    }
    private void saveToken(LoginUserResultPC data) {
        //Long time=60*60L;
        Long time=30*24*60*60L;
        Map<String,Object> claims= new HashMap<String,Object>();
        claims.put("userName",data.getUserName());
        claims.put("currentTime",new Date(System.currentTimeMillis()));
        String token = jwtTokenUtil.generateToken("PC_"+data.getUserId(),new Date(System.currentTimeMillis()+time*1000),claims);
        data.setToken(token);
        redis.set( "PC_"+data.getUserId(),data, time);
        List<CompanyBaseListResult> parks=data.getCompanys();
    }

   /**
     * 获取菜单
     * @return
     */
    @ApiOperation(value = "获取菜单",notes = "获取菜单,前端页面使用")
    @Override
    public BaseResultVo<MenuResultEntity> getMenus() throws Exception {
        List<MenuResultEntity> menus = loginService.getMenus();
        return BaseResultVo.success(menus);

    }

    /**
     * 移动端登录
     * @param loginParam
     * @return
     */
    @ApiOperation(value = "移动端登录",notes = "移动端登录,用于移动端登录使用,code为0时已注册，登录成功，为1时未注册")
    @Override
   public BaseResultVo<LoginUserResultMobile> loginMobile(@Validated LoginParam loginParam) throws Exception{
        LoginUserResultMobile resultVo = new LoginUserResultMobile();
       //校验登录
        String tel = loginParam.getTel();
        //校验登录
        if(loginService.isLegality(tel,loginParam.getPassword(),false)) {
            //获取当前登录用户
            UserManagement user = loginService.getUserByTel(tel,false);
            //查询当前登录用户角色信息
            List<LoginRole> roles = loginService.getRoles(user.getId());
            List<String> roleLevel = Lists.transform(roles, LoginRole->LoginRole.getRoleLevel());
            boolean flag = roleLevel.contains(com.sdkj.fixed.asset.common.core.RoleType.SYSADMIN.getRoleType());

            //查询登录用户所属公司
            Map<String, Object> companyInfoForHomePage = loginService.getCompanyInfoForHomePage(user.getId(), flag);
            List<CompanyBaseListResult> companys = (List<CompanyBaseListResult>) companyInfoForHomePage.get("companyId");
            resultVo.setLoginRoles(roles);
            resultVo.setUserId(user.getId());
            resultVo.setUserName(user.getName());
            resultVo.setUserTel(user.getTel());
            resultVo.setCompanys(companys);
            resultVo.setBelongToCompanyId((String) companyInfoForHomePage.get("belongToCompany"));
            //公司使用情况，版本号
            if(flag){
                resultVo.setVersion(3);
            } else {
                UsageManagement usageManagement = loginService.getUsage(companys.get(0).getCompanyId());
                resultVo.setVersion(usageManagement != null ? usageManagement.getType(): 3);
            }
            //基础信息
            saveTokenForApp(resultVo);
            return BaseResultVo.success(resultVo);
        }else{
            return BaseResultVo.failure("用户名或密码错误");
        }
   }
    private void saveTokenForApp(LoginUserResultMobile data) {
        //Long time=60*60L;
        Long time=30*24*60*60L;
        Map<String,Object> claims= new HashMap<String,Object>();
        claims.put("userName",data.getUserName());
        claims.put("currentTime",new Date(System.currentTimeMillis()));
        String token = jwtTokenUtil.generateToken("APP_"+data.getUserId(),new Date(System.currentTimeMillis()+time*1000),claims);
        data.setToken(token);
        redis.set( "APP_"+data.getUserId(),data, time);
        List<CompanyBaseListResult> parks=data.getCompanys();
    }
   /**
     * 退出登录
     * @return
     */
    @ApiOperation(value = "退出登录",notes = "退出登录")
    @Override
    public BaseResultVo LogOut() throws Exception {
        String token = request.getHeader("token");
        if(cacheUtil.getUserRole(token).contains(RoleType.SYSADMIN.getRoleType())){
            return BaseResultVo.success();
        }
        redis.del(jwtTokenUtil.getUserIdFromToken(token));
        //清除缓冲
        return BaseResultVo.success();
    }
    /**
     * 获取当前登录用户所属公司
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "获取当前登录用户所属公司",notes = "获取当前登录用户所属公司，用于刷新页面使用")
    @Override
    public BaseResultVo<CompanyBaseListResult> getCompanyOfUser() throws Exception {
        String token = request.getHeader("token");
        boolean flag = cacheUtil.getUserRole(token).contains(com.sdkj.fixed.asset.common.core.RoleType.SYSADMIN.getRoleType());
        //查询登录用户所属公司
        Map<String, Object> companyInfoForHomePage = loginService.getCompanyInfoForHomePage(cacheUtil.getUserId(token), flag);
        List<CompanyBaseListResult> companys = (List<CompanyBaseListResult>) companyInfoForHomePage.get("companyId");
        return BaseResultVo.success(companys);
    }


}
